<template>
  <div class="wrap">
  <el-tabs
    v-model="editableTabsValue"
    type="card"
    class="demo-tabs"
    closable
    @tab-remove="removeTab"
    @tab-click="handleTab"
  >
    <el-tab-pane
      v-for="item in editableTabs"
      :key="item.name"
      :label="item.title"
      :name="item.name"
    >
      <!-- {{ item.content }} -->
    </el-tab-pane>
  </el-tabs>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
let route = useRoute();
let router = useRouter();
onMounted(() => {
    // console.log(route.meta.title, "mounted");
});

const editableTabsValue = ref('')
const editableTabs = ref([])
// 添加tab
const addTab = (targetName,routePath) => {
  editableTabs.value.push({
    title: targetName,
    name: routePath,
  })
}
watch(route,()=>{
  // console.log(route, "watch");
  let routeTitle = route.meta.title
  let routePath = route.path 
  editableTabsValue.value = routePath

  let res = editableTabs.value.some((item)=>{
     return item.title == routeTitle
  })
  if(res == false){
    addTab(routeTitle,routePath)
  }
},{immediate:true })
// 标签变化
const handleTab=(e)=>{
  // console.log(e.props.name,"==");
  let path = e.props.name
  router.push(path)
}
// 关闭标签
const removeTab = (targetName) => {
  const tabs = editableTabs.value
  let activeName = editableTabsValue.value
  if (activeName === targetName) {
    tabs.forEach((item, index) => {
      if (item.name === targetName) {
        const nextTab = tabs[index + 1] || tabs[index - 1]
        if (nextTab) {
          activeName = nextTab.name
        }
      }
    })
  }

  editableTabsValue.value = activeName
  editableTabs.value = tabs.filter((tab) => tab.name !== targetName)
  // 拿到最后一项跳转
   let path = editableTabs.value[editableTabs.value.length -1].name
   router.push(path)
}
</script>

<style lang="scss" scoped>
::v-deep .el-tabs__header,.is-top{
  margin: 0 !important;
}
</style>